package com.AAL.DAO;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.classic.Session;

import com.AAL.DAO.Interface.IPurchaseInvoiceDetailDAO;
import com.AAL.Model.PurchaseInvoiceDetail;
import com.AAL.Utils.HibernateUtil;

public class PurchaseInvoiceDetailDAO implements IPurchaseInvoiceDetailDAO {

	@Override
	public PurchaseInvoiceDetail saveAndUpdatePurchaseInvoiceDetail(
			PurchaseInvoiceDetail purchaseInvoiceDetail) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try {
			session.saveOrUpdate(purchaseInvoiceDetail);
		} catch (Exception e) {
			return null;
		}
		session.getTransaction().commit();
		return purchaseInvoiceDetail;
	}

	@Override
	public PurchaseInvoiceDetail getPurchaseInvoiceDetail(
			int purchaseInvoiceDetailID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		PurchaseInvoiceDetail purchaseInvoiceDetail = (PurchaseInvoiceDetail) session
				.load(PurchaseInvoiceDetail.class, purchaseInvoiceDetailID);
		return purchaseInvoiceDetail;
	}

	@Override
	public PurchaseInvoiceDetail deletePurchaseInvoiceDetail(
			int purchaseInvoiceDetailID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();
			PurchaseInvoiceDetail purchaseInvoiceDetail = (PurchaseInvoiceDetail) session
					.load(PurchaseInvoiceDetail.class, purchaseInvoiceDetailID);
			if (null != purchaseInvoiceDetail) {
				session.delete(purchaseInvoiceDetail);
			}
			session.getTransaction().commit();
			return purchaseInvoiceDetail;
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
			return null;
		}
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public List<PurchaseInvoiceDetail> getLstPurchaseInvoiceDetailsByPurchaseInvoice(
			String purchaseInvoiceID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		List<PurchaseInvoiceDetail> purchaseInvoiceDetails = null;
		try {
			session.beginTransaction();
			purchaseInvoiceDetails=(List<PurchaseInvoiceDetail>)session.createQuery("from PurchaseInvoiceDetail where purchaseInvoice.purchaseInvoiceID=:purchaseID").setParameter("purchaseID", purchaseInvoiceID).list();

			session.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		
		return purchaseInvoiceDetails;
	}

}
